using System;
using System.Management;

namespace SoftwareLocker
{
    public static class SystemInfo
    {
        #region -> Private Variables

        public static bool UseProcessorId;
        public static bool UseBaseBoardProduct;
        public static bool UseBaseBoardManufacturer;
        public static bool UseDiskDriveSignature;
        public static bool UseVideoControllerCaption;
        public static bool UsePhysicalMediaSerialNumber;
        public static bool UseBiosVersion;
        public static bool UseBiosManufacturer;
        public static bool UseWindowsSerialNumber;

        #endregion

        public static string GetSystemInfo(string softwareName)
        {
            if(UseProcessorId)
                softwareName += RunQuery("Processor", "ProcessorId");

            if (UseBaseBoardProduct)
                softwareName += RunQuery("BaseBoard", "Product");

            if (UseBaseBoardManufacturer)
                softwareName += RunQuery("BaseBoard", "Manufacturer");

            if (UseDiskDriveSignature)
                softwareName += RunQuery("DiskDrive", "Signature");

            if (UseVideoControllerCaption)
                softwareName += RunQuery("VideoController", "Caption");

            if (UsePhysicalMediaSerialNumber)
                softwareName += RunQuery("PhysicalMedia", "SerialNumber");

            if (UseBiosVersion)
                softwareName += RunQuery("BIOS", "Version");

            if (UseWindowsSerialNumber)
                softwareName += RunQuery("OperatingSystem", "SerialNumber");

            softwareName = RemoveUseLess(softwareName);
            
            if (softwareName.Length < 25)
                return GetSystemInfo(softwareName);

            return softwareName.Substring(0, 25).ToUpper();
        }

        private static string RemoveUseLess(string st)
        {
            for (int i = st.Length - 1; i >= 0; i--)
            {
                char ch = char.ToUpper(st[i]);

                if ((ch < 'A' || ch > 'Z') &&
                    (ch < '0' || ch > '9'))
                {
                    st = st.Remove(i, 1);
                }
            }
            return st;
        }

        private static string RunQuery(string tableName, string methodName)
        {
            var mos = new ManagementObjectSearcher("Select * from Win32_" + tableName);
            foreach (ManagementObject mo in mos.Get())
            {
                try
                {
                    return mo[methodName].ToString();
                }
                catch(Exception e)
                {
                    System.Windows.Forms.MessageBox.Show(e.Message);
                }
            }
            return "";
        }
    }
}
